import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent, useRef, MutableRefObject } from 'react'
import {
  Space, Row, Col, Input,
  Form, Table, Modal, Card, InputNumber, Select, Switch
} from 'antd'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { DefaultOptionType } from 'antd/lib/select'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { IData, PagingSize, IResponseCodeType, DictionaryTypeModal, IFileAttributeAdminModal, IFileClassModel, IFileClassAttrModel } from '@/models/common'
import { DownOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './fileattributeadmin.scss'
import { TableRowSelection } from 'antd/lib/table/interface'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  enableModalOpen: boolean
  attrUpdateModalOpen: boolean
  /**
   * 当前修改行信息
   */
  attrUpdateRow: ColumnsDataType
  pageLoading: boolean
  /**
   * 表格数据
   */
  attrTableList: ColumnsDataType[]
  /**
   * 当前页码
   */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  dictOptions: DefaultOptionType[]
  notAuth: boolean
  selectedRowKeys: React.Key[]
  fileClassValue: string[]
  fileClassOptions: DefaultOptionType[]
  classAttrTableList: ColumnsDataType[]
}

const Index: FC = () => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      enableModalOpen: false,
      attrUpdateModalOpen: false,
      attrUpdateRow: {
        id: "",
        name: "",
        order_sort: "",
        dictionary_id: '',
        allow_user_input: "0",
        is_class_attribute: "0",
      },
      pageLoading: false,
      attrTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      dictOptions: [],
      notAuth: false,
      selectedRowKeys: [],
      fileClassValue: [],
      fileClassOptions: [],
      classAttrTableList: []
    }
  })

  useEffect(() => {
  }, [])

  const events = {
    //新增文件属性
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = ''
      ViewModel.attrUpdateRow.id = ''
      ViewModel.attrUpdateRow.order_sort = ''
      ViewModel.attrUpdateRow.dictionary_id = ''
      ViewModel.attrUpdateRow.allow_user_input = '0'
      ViewModel.attrUpdateRow.is_class_attribute = '0'
      ViewModel.attrUpdateModalOpen = true
      setData({ ...data })
    },
    //编辑文件属性
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = record.name
      ViewModel.attrUpdateRow.id = record.id
      ViewModel.attrUpdateRow.order_sort = record.order_sort
      ViewModel.attrUpdateRow.dictionary_id = record.dictionary_id
      ViewModel.attrUpdateRow.allow_user_input = record.allow_user_input
      ViewModel.attrUpdateRow.is_class_attribute = record.is_class_attribute
      ViewModel.attrUpdateModalOpen = true
      setData({ ...data })
    },
    //删除文件属性
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该属性吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteAttr(record.id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateAttrNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onDictUpdateOrderSortChange(value: number | string | null) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.order_sort = value as string
      setData({ ...data })
    },
    onDictChange(value: string) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.dictionary_id = value
      setData({ ...data })
    },
    onAllowUserInputChange(checked: boolean) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.allow_user_input = checked ? "1" : '0'
      setData({ ...data })
    },
    onAttrUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.attrUpdateRow.name) {
        util.alertTip('请输入属性名称')
        return
      }
      if (ViewModel.attrUpdateRow.id) {
        methods.requestUpdateAttr()
      } else {
        methods.requestAddAttr()
      }
    },
    onRoleUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = ''
      ViewModel.attrUpdateRow.id = ''
      ViewModel.attrUpdateModalOpen = false
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        // ViewModel.page = ViewModel.page + 1
        // ViewModel.pageLoading = true
        // setData({ ...data })
        // methods.querySubTableList()
      }
    },
    onClickEnable() {
      const { ViewModel } = data
      ViewModel.enableModalOpen = true
      ViewModel.selectedRowKeys = []
      ViewModel.fileClassValue = []
      ViewModel.classAttrTableList = []
      setData({ ...data })
    },
    onEnableOk() {
      const { ViewModel } = data
      if (ViewModel.selectedRowKeys.length == 0) {
        util.alertTip('请选择属性')
        return
      }
      methods.requestAddAttributeMetaFromClass()
    },
    onEnableCancel() {
      const { ViewModel } = data
      ViewModel.enableModalOpen = false
      setData({ ...data })
    },
    onFileClassChange(value: string[]) {
      const { ViewModel } = data
      ViewModel.fileClassValue = value
      setData({ ...data })
      methods.requestMultiClassAttributes()
    },
  }
  const methods = {
    /**
     * 加载文件属性
     */
    async requestAttrList() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getFileAttributeAdminList<IFileAttributeAdminModal>(null)
      const { code, data: fileAttributeAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { attribute_meta_list = [] } = fileAttributeAdminData
        ViewModel.attrTableList = [...attribute_meta_list]
        if (attribute_meta_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = false
        }
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 加载字典
     */
    async requestDictionaryTypeList() {
      const { ViewModel } = data
      let res = await api.common.getAllDictionaryTypes<DictionaryTypeModal>(null)
      const { code, data: DictionaryTypeData, message } = res
      if (code == IResponseCodeType.Success) {
        let { type_list = [] } = DictionaryTypeData
        ViewModel.dictOptions = type_list.map((o) => {
          return {
            label: o.type_label,
            value: o.id
          }
        })
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 加载全部文件分类
     */
    async requestClassAdminList() {
      const { ViewModel } = data
      let res = await api.common.getFileClassList<IFileClassModel>(null)
      let { code, message, data: classTreeData, } = res
      if (code == IResponseCodeType.Success) {
        let { class_list = [] } = classTreeData
        ViewModel.fileClassOptions = class_list.map(o => {
          return {
            label: o.class_name,
            value: o.class_id
          }
        })
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 获取多选文件分类情况下的属性列表
     */
    async requestMultiClassAttributes() {
      const { ViewModel } = data
      let res = await api.common.getMultiClassAttributes<IFileClassAttrModel>({
        class_ids: JSON.stringify(ViewModel.fileClassValue)
      })
      let { code, message, data: classTreeData, } = res
      if (code == IResponseCodeType.Success) {
        let { attribute_list = [] } = classTreeData
        ViewModel.classAttrTableList = [...attribute_list]
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 从分类属性中添加文件属性
     */
    async requestAddAttributeMetaFromClass() {
      const { ViewModel } = data
      let res = await api.common.addAttributeMetaFromClass<IFileClassAttrModel>({
        ids: JSON.stringify(ViewModel.selectedRowKeys)
      })
      let { code, message, } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        events.onEnableCancel()
        methods.requestAttrList()
      }
    },
    /**
     * 新增文件属性
     */
    async requestAddAttr() {
      const { ViewModel } = data
      let res = await api.common.addFileAttribute({
        name: ViewModel.attrUpdateRow.name,
        order_sort: ViewModel.attrUpdateRow.order_sort,
        dictionary_id: ViewModel.attrUpdateRow.dictionary_id,
        allow_user_input: ViewModel.attrUpdateRow.allow_user_input,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.attrUpdateRow.name = ''
        ViewModel.attrUpdateRow.id = ''
        ViewModel.attrUpdateRow.order_sort = ''
        ViewModel.attrUpdateRow.allow_user_input = '0'
        ViewModel.attrUpdateRow.is_class_attribute = '0'
        ViewModel.attrUpdateModalOpen = false
        setData({ ...data })
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 更新文件属性
     */
    async requestUpdateAttr() {
      const { ViewModel } = data
      let res = await api.common.updateFileAttribute({
        name: ViewModel.attrUpdateRow.name,
        id: ViewModel.attrUpdateRow.id,
        order_sort: ViewModel.attrUpdateRow.order_sort,
        dictionary_id: ViewModel.attrUpdateRow.dictionary_id,
        allow_user_input: ViewModel.attrUpdateRow.allow_user_input,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.attrUpdateRow.name = ''
        ViewModel.attrUpdateRow.id = ''
        ViewModel.attrUpdateRow.order_sort = ''
        ViewModel.attrUpdateRow.allow_user_input = '0'
        ViewModel.attrUpdateRow.is_class_attribute = '0'
        ViewModel.attrUpdateModalOpen = false
        setData({ ...data })
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除文件属性
     * @param id 
     */
    async requestDeleteAttr(id: string) {
      let res = await api.common.deleteFileAttribute<null>({
        id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '排序号',
          align: "left",
          key: 'order_sort',
          dataIndex: 'order_sort',
        },
        {
          title: '名称',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '数据字典',
          align: "left",
          key: 'dictionary_name',
          dataIndex: 'dictionary_name',
        },
        {
          title: '是否可编辑',
          align: "left",
          key: 'allow_user_input_name',
          dataIndex: 'allow_user_input_name',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                修改
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                删除
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    createClassAttrColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '分类名称',
          align: "left",
          key: 'class_name',
          dataIndex: 'class_name',
        },
        {
          title: '属性名称',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
      ]
      return columns
    },
    createRowSelection(): TableRowSelection<ColumnsDataType> {
      return {
        selectedRowKeys: data.ViewModel.selectedRowKeys,
        type: 'checkbox',
        preserveSelectedRowKeys: true,
        onChange: (selectedRowKeys: React.Key[], selectedRows: ColumnsDataType[]) => {
          // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
          const { ViewModel } = data
          ViewModel.selectedRowKeys = selectedRowKeys
          setData({ ...data })
        },
      }
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Card title="文件属性管理">
          <Col className='fileattr-admin-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickAddRow}>新增</XlButtonFC>
                  <XlButtonFC type='default' onClick={events.onClickEnable}>启用</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.attrTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                <Table
                  scroll={{
                    x: '100%',
                    y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  rowKey='id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.attrTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Row>
          </Col>
        </Card>
        {/* 添加修改弹出框 */}
        <XlModalFC
          open={data.ViewModel.attrUpdateModalOpen}
          onOk={events.onAttrUpdateRowOk}
          onCancel={events.onRoleUpdateRowCancel}
          title='新增/修改'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
          >
            <Form.Item
              label="属性名称"
              required
            >
              <Input value={data.ViewModel.attrUpdateRow.name} onChange={events.onUpdateAttrNameChange} allowClear placeholder='请输入属性名称' disabled={data.ViewModel.attrUpdateRow.is_class_attribute == '1'} />
            </Form.Item>
            <Form.Item
              label="数据字典"
            >
              <Select
                disabled={data.ViewModel.attrUpdateRow.is_class_attribute == '1'}
                style={{ width: "100%" }}
                options={data.ViewModel.dictOptions}
                placeholder='请选择'
                allowClear
                value={data.ViewModel.attrUpdateRow.dictionary_id || undefined}
                onChange={events.onDictChange}
              />
            </Form.Item>
            <Form.Item
              label="排序号"
            >
              <InputNumber value={data.ViewModel.attrUpdateRow.order_sort} onChange={events.onDictUpdateOrderSortChange} placeholder='请输入排序号' style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              label="是否可编辑"
            >
              <Switch checked={data.ViewModel.attrUpdateRow.allow_user_input == '1'} onChange={events.onAllowUserInputChange} />
            </Form.Item>
          </Form>
        </XlModalFC>
        {/* 启用弹出框 */}
        <XlModalFC
          open={data.ViewModel.enableModalOpen}
          onOk={events.onEnableOk}
          onCancel={events.onEnableCancel}
          title='启用'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            autoComplete="off"
            style={{ paddingLeft: 15, paddingRight: 15 }}
          >
            <Form.Item
              label="文件分类"
            >
              <Select
                showArrow
                options={data.ViewModel.fileClassOptions}
                placeholder='请选择文件分类'
                mode='multiple'
                allowClear
                style={{ width: '100%' }}
                value={data.ViewModel.fileClassValue}
                onChange={events.onFileClassChange}
                maxTagCount={'responsive'}
                filterOption={(input, option) =>
                  ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                }
              />
            </Form.Item>
            <Form.Item noStyle>
              <Table
                scroll={{
                  x: '100%',
                  y: 400
                }}
                tableLayout='fixed'
                rowKey='id'
                pagination={false}
                columns={methods.createClassAttrColumns()}
                dataSource={data.ViewModel.classAttrTableList}
                rowSelection={methods.createRowSelection()}
              />
            </Form.Item>
          </Form>
        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default Index
